<template>
  <div class="permission-container">
    <!-- 搜索和操作栏 -->
    <el-card shadow="never" class="mb-4">
      <div class="flex justify-between items-center">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入权限名称/标识"
          style="width: 300px"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>

        <div>
          <el-button type="primary" :icon="Plus" @click="handleCreate">
            新增权限
          </el-button>
          <el-button :icon="Refresh" @click="refreshPermissionTree"> 刷新 </el-button>
        </div>
      </div>
    </el-card>

    <!-- 权限树形表格 -->
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="filteredPermissionList"
        row-key="id"
        border
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :expand-row-keys="expandedKeys"
        default-expand-all
      >
        <el-table-column prop="name" label="权限名称" min-width="200">
          <template #default="{ row }">
            <span v-if="row.type === 'menu'">
              <el-icon v-if="row.icon"><component :is="row.icon" /></el-icon>
              {{ row.name }}
            </span>
            <el-tag v-else :type="getTagType(row.type)">
              {{ row.name }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="code" label="权限标识" width="200" />

        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTagType(row.type)">
              {{ getTypeName(row.type) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="path" label="路径" width="180" />

        <el-table-column prop="sort" label="排序" width="80" align="center" />

        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              :icon="Edit"
              @click="handleEdit(row)"
            />
            <el-button
              size="small"
              type="danger"
              :icon="Delete"
              @click="handleDelete(row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 权限表单对话框 -->
    <PermissionFormDialog
      v-model="dialog.visible"
      :mode="dialog.mode"
      :current-data="dialog.currentData"
      :permission-tree="permissionList"
      @success="refreshPermissionTree"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref,reactive, computed, onMounted } from 'vue'
import { Search, Plus, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { usePermissionStore } from '@/stores/modules/permission'
import PermissionFormDialog from '@/components/ui/PermissionFormDialog.vue'
import type { PermissionItem } from '@/api/types/system'

const permissionStore = usePermissionStore()

// 权限数据
const loading = ref(false)
const permissionList = ref<PermissionItem[]>([])
const expandedKeys = ref<string[]>([])
const searchKeyword = ref('')

// 对话框控制
const dialog = reactive({
  visible: false,
  mode: 'create' as 'create' | 'edit',
  currentData: {} as Partial<PermissionItem>
})

// 获取权限列表
const fetchPermissionList = async () => {
  try {
    loading.value = true
    // const data = await permissionStore.getPermissionTree()
    // permissionList.value = data
    // // 默认展开所有节点
    // expandedKeys.value = flattenTree(data).map(item => item.id)
  } finally {
    loading.value = false
  }
}

// 扁平化树形数据用于搜索
const flattenTree = (tree: PermissionItem[]): PermissionItem[] => {
  return tree.reduce((acc, node) => {
    acc.push(node)
    if (node.children && node.children.length) {
      acc.push(...flattenTree(node.children))
    }
    return acc
  }, [] as PermissionItem[])
}

// 过滤权限列表
const filteredPermissionList = computed(() => {
  if (!searchKeyword.value) return permissionList.value

  const keyword = searchKeyword.value.toLowerCase()
  const filterNode = (nodes: PermissionItem[]): PermissionItem[] => {
    return nodes
      .filter((node) =>
        node.name.toLowerCase().includes(keyword) ||
        node.code.toLowerCase().includes(keyword))
      .map((node:any) => ({
        ...node,
        children: node.children ? filterNode(node.children) : undefined
      }))
  }

  return filterNode(JSON.parse(JSON.stringify(permissionList.value)))
})
type PermissionType = 'menu' | 'button' | 'api'
// 类型显示
const getTypeName = (type: PermissionType) => {
  const typeMap = {
    menu: '菜单',
    button: '按钮',
    api: '接口'
  }
  return typeMap[type] || type
}

const getTagType = (type: PermissionType) => {
  const typeMap = {
    menu: '',
    button: 'warning',
    api: 'success'
  }
  return typeMap[type] || 'info'
}

// 操作处理
const handleSearch = () => {
  // 搜索时收起所有节点
  expandedKeys.value = []
}

const refreshPermissionTree = () => {
  fetchPermissionList()
}

const handleCreate = () => {
  dialog.mode = 'create'
  dialog.currentData = {
    type: 'menu',
    status: 1,
    sort: 0,
    parentId: undefined
  }
  dialog.visible = true
}

const handleEdit = (row: PermissionItem) => {
  dialog.mode = 'edit'
  dialog.currentData = { ...row }
  dialog.visible = true
}

const handleDelete = async (row: PermissionItem) => {
  try {
    await ElMessageBox.confirm(
      `确定删除权限 "${row.name}" 吗？删除后不可恢复！`,
      '警告',
      { type: 'warning' }
    )
    await permissionStore.deletePermission(row.id)
    ElMessage.success('删除成功')
    refreshPermissionTree()
  } catch {
    // 用户取消
  }
}

const handleStatusChange = async (row: PermissionItem) => {
  try {
    await permissionStore.updatePermission({
      id: row.id,
      status: row.status
    })
    ElMessage.success('状态更新成功')
  } catch {
    // 失败时恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 初始化加载
onMounted(() => {
  fetchPermissionList()
})
</script>

<style lang="scss" scoped>
.permission-container {
  :deep(.el-table) {
    .el-table__row {
      .el-icon {
        margin-right: 5px;
      }

      // 不同类型行的样式
      &[data-type="menu"] {
        font-weight: 500;
      }

      &[data-type="button"] {
        color: var(--el-color-warning);
      }

      &[data-type="api"] {
        color: var(--el-color-success);
      }
    }
  }

  .mb-4 {
    margin-bottom: 1rem;
  }
}
</style>
